#include "card_io.h"
#include "card.h"


static u32 m_sector;
static u16 m_pos;

bool cardIO_init()
{
	m_sector = 0;
	m_pos = 0;

	return card_init();
}

void cardIO_seek(u32 sector, u16 pos)
{
	if (sector != m_sector)
	{
		//get rid of all remaining bytes
		while (m_pos < 512)
		{
			card_read();
			m_pos++;
		}

		card_setSector(sector);
		m_sector = sector;
		m_pos = 0;
	}

	while (m_pos < pos)
	{
		card_read();
		m_pos++;
	}
}

void cardIO_skip(u16 count)
{
	for (u16 i=0; i<count; i++)
	{
		card_read();
		m_pos++;
	}
}

void cardIO_read(void *buf, u16 sz)
{
	u8* b = (u8*) buf;

	for (int i=0; i<sz; i++)
	{
		if (m_pos == 512)
		{
			cardIO_seek(m_sector+1, 0);
		}

		*b = card_read();
		b++;
		m_pos++;
	}
}

u8 cardIO_readU8()
{
	u8 v;

	cardIO_read(&v, sizeof(v));

	return v;
}

u16 cardIO_readU16()
{
	u16 v;

	cardIO_read(&v, sizeof(v));

	return v;
}

u32 cardIO_readU32()
{
	u32 v;

	cardIO_read(&v, sizeof(v));

	return v;
}


